package com.ruoyi.web.controller.merchantTransaction;

import com.ruoyi.basedata.domain.ConfirmResult;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SignUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.merchant.domain.MpMerchant;
import com.ruoyi.merchant.domain.MpMerchantRSP;
import com.ruoyi.merchant.service.IMpMerchantService;
import com.ruoyi.merchantTransaction.domain.MerchantTransactionPay;
import com.ruoyi.merchantTransaction.domain.MerchantTransactionPayExport;
import com.ruoyi.merchantTransaction.service.IMerchantTransactionPayService;
import com.ruoyi.transaction.domain.TransactionPay;
import com.ruoyi.transaction.domain.TransactionPayExport;
import com.ruoyi.withdrawalParam.domain.PayCheckRsp;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *  信息操作处理
 * 
 * @author ruoyi
 * @date 2019-05-07
 */
@Controller
@RequestMapping("/merchantTransaction/transactionPay")
public class MerchantTransactionPayController extends BaseController
{
	Logger log = LoggerFactory.getLogger(MerchantTransactionPayController.class);
    private String prefix = "merchantTransaction/transactionPay";
	
	@Autowired
	private IMerchantTransactionPayService transactionPayService;
	@Autowired
	private IMpMerchantService mpMerchantService;

	// 商户交易-支付交易  支付状态查询URL - 外部
	@Value("${reqUrlConfig.merchantCheckPay}")
	private String merchantCheckPay;
	// 商户交易-支付交易  通知状态查询URL - 内部
	@Value("${reqUrlConfig.managerNotifyPay}")
	private String managerNotifyPay;

	@RequiresPermissions("merchantTransaction:transactionPay:view")
	@GetMapping()
	public String transactionPay()
	{
	    return prefix + "/transactionPay";
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("merchantTransaction:transactionPay:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(MerchantTransactionPay transactionPay)
	{
		MpMerchant mpMerchant = new MpMerchant();
		mpMerchant.setUserId(ShiroUtils.getUserId().intValue());
		List<MpMerchantRSP> mpMerchantRSPS = mpMerchantService.selectMpMerchantList(mpMerchant);
		if(mpMerchantRSPS.size() > 0){
			MpMerchantRSP mpMerchantRSP = mpMerchantRSPS.get(0);
			transactionPay.setMerchantId(mpMerchantRSP.getId());
		}else {
			transactionPay.setMerchantId(0L);
		}
		startPage();
        List<MerchantTransactionPay> list = transactionPayService.selectTransactionPayList(transactionPay);
		return getDataTable(list);
	}




	/**
	 * 导出列表
	 */
	@RequiresPermissions("merchantTransaction:transactionPay:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(MerchantTransactionPay transactionPay)
    {
		MpMerchant mpMerchant = new MpMerchant();
		mpMerchant.setUserId(ShiroUtils.getUserId().intValue());
		List<MpMerchantRSP> mpMerchantRSPS = mpMerchantService.selectMpMerchantList(mpMerchant);
		if(mpMerchantRSPS.size() > 0){
			MpMerchantRSP mpMerchantRSP = mpMerchantRSPS.get(0);
			transactionPay.setMerchantId(mpMerchantRSP.getId());
		}else {
			transactionPay.setMerchantId(0L);
		}
    	List<MerchantTransactionPay> list = transactionPayService.selectTransactionPayList(transactionPay);
		List<MerchantTransactionPayExport> payExportList = dataConvert(list);
		ExcelUtil<MerchantTransactionPayExport> util = new ExcelUtil<MerchantTransactionPayExport>(MerchantTransactionPayExport.class);
        return util.exportExcel(payExportList, "transactionPay");
    }


	/**
	 * 导出数据转化   分=>元   状态转化
	 */
	public static List<MerchantTransactionPayExport> dataConvert(List<MerchantTransactionPay> list) {
		List<MerchantTransactionPayExport> exportList = new ArrayList<>();
		for (MerchantTransactionPay transactionPay : list) {
			MerchantTransactionPayExport transactionPayExport = new MerchantTransactionPayExport();
			BeanUtils.copyProperties(transactionPay, transactionPayExport);
			BigDecimal yuan = new BigDecimal("100");
			// 支付金额
			transactionPayExport.setFee(transactionPay.getFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 申请金额
			transactionPayExport.setSubFee(transactionPay.getSubFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));

			// 商户入账
			transactionPayExport.setMchFee(transactionPay.getMchFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));

			// 状态转化
			if (transactionPay.getStatus() == 1) {
				transactionPayExport.setPayStatus("下单失败");
			}else if (transactionPay.getStatus() == 2) {
				transactionPayExport.setPayStatus("下单超时");
			}else if (transactionPay.getStatus() == 3) {
				transactionPayExport.setPayStatus("待支付");
			}else if (transactionPay.getStatus() == 4) {
				transactionPayExport.setPayStatus("未支付");
			}else if (transactionPay.getStatus() == 5) {
				transactionPayExport.setPayStatus("已支付");
			}

			if (transactionPay.getStatus() == 4 || transactionPay.getStatus() == 5) {
				if (transactionPay.getMerchantNotifyStatus() == 0) {
					transactionPayExport.setNotifyStatus("未通知");
				}else if (transactionPay.getMerchantNotifyStatus() == 1) {
					transactionPayExport.setNotifyStatus("已通知");
				}

			}else {
				transactionPayExport.setNotifyStatus("无效");
			}

			exportList.add(transactionPayExport);
		}
		return exportList;
	}




	/**
	 * 新增
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存
	 */
	@RequiresPermissions("merchantTransaction:transactionPay:add")
	@Log(title = "", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(MerchantTransactionPay transactionPay)
	{		
		return toAjax(transactionPayService.insertTransactionPay(transactionPay));
	}

	/**
	 * 修改
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap)
	{
		MerchantTransactionPay transactionPay = transactionPayService.selectTransactionPayById(id);
		mmap.put("transactionPay", transactionPay);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存
	 */
	@RequiresPermissions("merchantTransaction:transactionPay:edit")
	@Log(title = "", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(MerchantTransactionPay transactionPay)
	{		
		return toAjax(transactionPayService.updateTransactionPay(transactionPay));
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("merchantTransaction:transactionPay:remove")
	@Log(title = "", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(transactionPayService.deleteTransactionPayByIds(ids));
	}

	@PostMapping("/payConfirm")
	@ResponseBody
	public AjaxResult payConfirm(Long id){
		MerchantTransactionPay confirmPay = transactionPayService.selectTransactionPayById(id);
		Long merchantId = confirmPay.getMerchantId();
		MpMerchant merchant = mpMerchantService.selectMpMerchantById(merchantId);
		String key = merchant.getSecretKey();
		String data = "mch_id=" + confirmPay.getMerchantCode() + "&out_trade_no=" + confirmPay.getMchCode();
		// 进行签名
		String sign = SignUtil.getSignReq(data, key);
		data += "&sign=" + sign;
		log.info("请求的报文：" + data);
		// 发起请求
		String result = HttpUtils.sendPost(merchantCheckPay, data, false);
		if (StringUtils.isNotEmpty(result)) {
			JSONObject jsonObjectResult = JSONObject.fromObject(result);
			PayCheckRsp payCheckRsp = (PayCheckRsp) net.sf.json.JSONObject.toBean(jsonObjectResult, PayCheckRsp.class);
			if (payCheckRsp.getStatus() == 1) {
				return AjaxResult.success("已支付");
			}else {
				return AjaxResult.error("未支付");
			}
		}else {
			return AjaxResult.error("请求失败!");
		}
	}

	@PostMapping("/merchantNotify")
	@ResponseBody
	public AjaxResult merchantNotify(Long id) {
		MerchantTransactionPay confirmPay = transactionPayService.selectTransactionPayById(id);
		JSONObject jsonObject = new JSONObject();
		// jsonObject.put("type",0);
		jsonObject.put("code",confirmPay.getCode());
		String  toJson = jsonObject.toString();
		String result = HttpUtils.sendPost(managerNotifyPay, toJson, false);
		if (StringUtils.isNotEmpty(result)) {
			JSONObject jsonObjectResult = JSONObject.fromObject(result);
			ConfirmResult confirmResult = (ConfirmResult) net.sf.json.JSONObject.toBean(jsonObjectResult, ConfirmResult.class);
			if (confirmResult.getStatus() == 0) {
				return AjaxResult.success(confirmResult.getMsg());
			}else {
				return AjaxResult.error(confirmResult.getMsg());
			}
		}else {
			return AjaxResult.error("请求失败!");
		}
	}
}
